import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

// 配置项目路由
const router = new VueRouter({
  routes: [
    {
      path: "/",
      redirect: "/home", // 重定向
    },
    {
      path: "/home", //首页
      name: "Home",
      component: () => import("@/views/home/Home"),
      children: [
        // 二级路由 不能加'/' 加'/'表示一级路由
        {
          path: "searchPopup",
          component: () => import("@/views/home/search/searchPopup.vue"),
          name: "searchpopup",
          meta: {
            isshowtabbar: false,
          },
        },
      ],
      meta: {
        isShowTabbar: true,
      },
    },

    {
      path: "/topic", //专题
      name: "Topic",
      component: () => import("@/views/topic/Topic"),
      meta: {
        isShowTabbar: true,
      },
    },
    {
      path: "/category", //分类
      name: "Category",
      component: () => import("@/views/category/Category"),
      meta: {
        isShowTabbar: true,
      },
    },
    {
      path: "/cart", //购物车
      name: "Cart",
      component: () => import("@/views/cart/Cart"),
      meta: {
        isShowTabbar: true,
      },
    },
    {
      path: "/user", //我的
      name: "User",
      component: () => import("@/views/user/User"),
      meta: {
        isShowTabbar: true,
      },
    },
    {
      path: "/productDetail", //产品详情
      name: "ProductDetail",
      component: () => import("@/views/productdetail/ProductDetail"),
    },
    {
      path: "/channel", // 产品分类页面（从首页类别点进去如 居家-餐厨-配件。。。 ）
      name: "Channel",
      component: () => import("@/views/channel/Channel.vue"),
    },
    {
      path: "/brand", // 品牌
      name: "brand",
      component: () => import("@/views/brand/Brand.vue"),
    },
  ],
});

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 有token就表示已经登录
  // 想要进入购物车页面，必须有登录标识token
  // console.log('to:', to)
  // console.log('from:', from)
  let token = localStorage.getItem("token");
  if (to.path == "/cart") {
    // 此时必须要有token
    if (token) {
      next(); // next()去到to所对应的路由界面
    } else {
      Vue.prototype.$toast("请先登录");
      // 定时器
      setTimeout(() => {
        next("/user"); // 强制去到"/user"所对应的路由界面
      }, 1000);
    }
  } else {
    // 如果不是去往购物车的路由，则直接通过守卫，去到to所对应的路由界面
    next();
  }
});

// 该段代码不需要记，理解即可
// 在vue-router在3.1.0版本之后，push和replace方法会返回一个promise对象，如果跳转到相同的路由，就报promise uncaught异常
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

export default router;
